package example.juc3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestReentrantLock {
    /**
     * 可重入锁，加锁和释放次数要匹配，否则其他线程无法获得锁
     */
    public static void main(String[] args) {

        Lock lock = new ReentrantLock();

        new Thread(() -> {
            lock.lock();
            lock.lock();
            try {
                System.out.println("外层");
                lock.lock();
                try {
                    System.out.println("内层");
                } finally {
                    lock.unlock();
                }
            } finally {
                lock.unlock();
                lock.unlock();
            }

        },"t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println("2");
            } finally {
                lock.unlock();
            }
        },"t2").start();

    }
}
